package com.trkj.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trkj.wiki.mapper.EbookMapper;
import com.trkj.wiki.pojo.Ebook;
import com.trkj.wiki.pojo.EbookExample;
import com.trkj.wiki.req.EbookQueryReq;
import com.trkj.wiki.req.EbookSaveReq;
import com.trkj.wiki.resp.EbookQueryResp;
import com.trkj.wiki.resp.PageResp;
import com.trkj.wiki.util.CopyUtil;
import com.trkj.wiki.util.SnowFlake;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Log4j2
@Service
public class EbookService {
    @Autowired
    private EbookMapper ebookMapper;
    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req){
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if(!ObjectUtils.isEmpty(req.getName())){
            criteria.andNameLike("%"+req.getName()+"%");
        }
        if(!ObjectUtils.isEmpty(req.getCategory2Id())){
            criteria.andCategory2IdEqualTo(req.getCategory2Id());
        }
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);
        PageInfo<Ebook> pageInfo=new PageInfo<>(ebookList);
        log.info("总行数：{}",pageInfo.getTotal());
        log.info("总页数：{}",pageInfo.getPages());

    /*    List<EbookResp> respList=new ArrayList<>();
        for (Ebook ebook : ebookList) {
            EbookResp ebookResp = new EbookResp();
            BeanUtils.copyProperties(ebook,ebookResp);
            respList.add(ebookResp);
        }*/

        List<EbookQueryResp> respList = CopyUtil.copyList(ebookList, EbookQueryResp.class);
        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(respList);


        return pageResp;
    }
    
    /**
     * @Author Twx
     * @Date 2021/4/25 14:34
     * @Description 电子书新增/修改
     * @Param [req]
     * @Return void
     * @Since version-1.0
     */
    public void save(EbookSaveReq req){
        Ebook ebook=CopyUtil.copy(req,Ebook.class);
        if(ObjectUtils.isEmpty(req.getId())){
            //新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        }else {
            //更新
            ebookMapper.updateByPrimaryKey(ebook);
        }

    }

    /*
     * @Author Twx
     * @Date 2021/4/25 20:28
     * @Description 删除电子书
     * @Param [id]
     * @Return void
     * @Since version-1.0
     */
    public void delete(long id){
        ebookMapper.deleteByPrimaryKey(id);
    }

}
